package com.jsh.erp.service;

import com.jsh.erp.constants.BusinessConstants;
import com.jsh.erp.datasource.entities.Person;
import com.jsh.erp.datasource.entities.PersonExample;
import com.jsh.erp.datasource.entities.Prescription;
import com.jsh.erp.datasource.entities.PrescriptionExample;
import com.jsh.erp.datasource.entities.Supplier;
import com.jsh.erp.datasource.mappers.PersonMapper;
import com.jsh.erp.datasource.mappers.PrescriptionMapper;
import com.jsh.erp.datasource.mappers.SupplierMapper;
import com.jsh.erp.datasource.mappers.SupplierMapperEx;
import com.jsh.erp.exception.JshException;
import com.jsh.erp.utils.PageUtils;
import com.jsh.erp.utils.StringUtil;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

/**
 * @author hanle
 * @description
 * @date 2025/6/8 11:10
 * @Company 西安图迹信息科技有限公司
 */
@Service
public class PrescriptionService {
   private Logger logger = LoggerFactory.getLogger(PrescriptionService.class);

   @Resource
   private PrescriptionMapper prescriptionMapper;
   @Resource
   private SupplierMapperEx supplierMapperEx;
   @Resource
   private PersonMapper personMapper;

   /**
    * 根据ID获取处方信息
    *
    * @param id 处方ID
    * @return 处方信息
    * @throws Exception
    */
   public Prescription getPrescription(Long id) throws Exception {
      Prescription result = null;
      try {
         result = prescriptionMapper.selectByPrimaryKey(id);
      }
      catch(Exception e) {
         JshException.readFail(logger, e);
      }
      return result;
   }

   /**
    * 获取所有处方信息
    *
    * @return 处方信息列表
    * @throws Exception
    */
   public List<Prescription> getAllPrescriptions() throws Exception {
      List<Prescription> list = null;
      try {
         PrescriptionExample example = new PrescriptionExample();
         example.createCriteria();
         list = prescriptionMapper.selectByExample(example);
      }
      catch(Exception e) {
         JshException.readFail(logger, e);
      }
      return list;
   }

   /**
    * 根据条件查询处方信息
    *
    * @param customerId 客户ID
    * @return 处方信息列表
    * @throws Exception
    */
   public List<Prescription> searchPrescriptions(Long customerId) throws Exception {
      List<Prescription> list = null;
      try {
         PageUtils.startPage();
         PrescriptionExample example = new PrescriptionExample();
         PrescriptionExample.Criteria criteria = example.createCriteria();
         example.setOrderByClause("create_time desc");

         if(customerId != null) {
            criteria.andCustomerIdEqualTo(customerId);
         }

         list = prescriptionMapper.selectByExample(example);
      }
      catch(Exception e) {
         JshException.readFail(logger, e);
      }

      List<Long> customerIds = list.stream().map(Prescription::getCustomerId).distinct().collect(Collectors.toList());

      if(!CollectionUtils.isEmpty(customerIds)) {
         List<Supplier> supplierList = supplierMapperEx.selectByIds(customerIds, "客户");
         Map<Long, String> supplierMap = supplierList.stream()
            .filter(obj -> StringUtil.isNotEmpty(obj.getSupplier()))
            .collect(Collectors.toMap(Supplier::getId, Supplier::getSupplier, (k1, k2) -> k2));
         Map<Long, String> supplierMobileMap = supplierList.stream()
            .filter(obj -> StringUtil.isNotEmpty(obj.getPhoneNum()))
            .collect(Collectors.toMap(Supplier::getId, Supplier::getPhoneNum, (k1, k2) -> k2));

         list.forEach(prescription -> {
            prescription.setCustomerName(supplierMap.get(prescription.getCustomerId()));
            prescription.setCustomerMobile(supplierMobileMap.get(prescription.getCustomerId()));
         });
      }

      List<Long> optometrists = list.stream()
         .map(Prescription::getOptometrist)
         .filter(Objects::nonNull)
         .map(Long::valueOf)
         .distinct()
         .collect(Collectors.toList());

      if(!CollectionUtils.isEmpty(optometrists)) {
         PersonExample personExample = new PersonExample();
         personExample.createCriteria().andIdIn(optometrists);
         List<Person> personList = personMapper.selectByExample(personExample);
         Map<Long, String> personMap = personList.stream()
            .filter(obj -> StringUtil.isNotEmpty(obj.getName()))
            .collect(Collectors.toMap(Person::getId, Person::getName, (k1, k2) -> k2));

         list.forEach(prescription -> {
            if(StringUtil.isNotEmpty(prescription.getOptometrist())) {
               prescription.setOptometristName(personMap.get(Long.valueOf(prescription.getOptometrist())));
            }
         });
      }

      return list;
   }

   /**
    * 新增处方信息
    *
    * @param prescription 处方信息
    * @return 操作结果
    * @throws Exception
    */
   @Transactional(rollbackFor = Exception.class)
   public int createPrescription(Prescription prescription) throws Exception {
      int result = 0;
      try {
         prescription.setCreateTime(new Date());
         result = prescriptionMapper.insertSelective(prescription);
      }
      catch(Exception e) {
         JshException.writeFail(logger, e);
      }
      return result;
   }

   /**
    * 添加处方信息返回id
    *
    * @param prescription
    * @return
    * @throws Exception
    */
   @Transactional(rollbackFor = Exception.class)
   public Long createPrescription2(Prescription prescription) throws Exception {
      int result = 0;
      try {
         prescription.setCreateTime(new Date());
         result = prescriptionMapper.insertSelective2(prescription);
      }
      catch(Exception e) {
         JshException.writeFail(logger, e);
      }
      return prescription.getId();
   }

   /**
    * 更新处方信息
    *
    * @param prescription 处方信息
    * @return 操作结果
    * @throws Exception
    */
   @Transactional(rollbackFor = Exception.class)
   public int updatePrescription(Prescription prescription) throws Exception {
      int result = 0;
      try {
         result = prescriptionMapper.updateByPrimaryKeySelective(prescription);
      }
      catch(Exception e) {
         JshException.writeFail(logger, e);
      }
      return result;
   }

   /**
    * 删除处方信息
    *
    * @param id 处方ID
    * @return 操作结果
    * @throws Exception
    */
   @Transactional(rollbackFor = Exception.class)
   public int deletePrescription(Long id) throws Exception {
      int result = 0;
      try {
         result = prescriptionMapper.deleteByPrimaryKey(id);
      }
      catch(Exception e) {
         JshException.writeFail(logger, e);
      }
      return result;
   }

   /**
    * 批量删除处方信息
    *
    * @param ids 处方ID列表
    * @return 操作结果
    * @throws Exception
    */
   @Transactional(rollbackFor = Exception.class)
   public int batchDeletePrescriptions(List<Long> ids) throws Exception {
      int result = 0;
      try {
         PrescriptionExample example = new PrescriptionExample();
         example.createCriteria().andIdIn(ids);
         result = prescriptionMapper.deleteByExample(example);
      }
      catch(Exception e) {
         JshException.writeFail(logger, e);
      }
      return result;
   }

   public Prescription getLatestPrescription(Long customerId) {
      try {
         PrescriptionExample example = new PrescriptionExample();
         PrescriptionExample.Criteria criteria = example.createCriteria();
         criteria.andCustomerIdEqualTo(customerId);
         criteria.andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
         example.setOrderByClause("create_time desc");

         List<Prescription> prescriptions = prescriptionMapper.selectByExample(example);

         if(prescriptions != null && !prescriptions.isEmpty()) {
            return prescriptions.get(0);
         }
      }
      catch(Exception e) {
         JshException.writeFail(logger, e);
      }

      return null;
   }
}
